<template>
  <div>
    <div class="SelectApp">
      <span>{{ $t("module.role.sourceApplication") }}:</span>
      <Select v-model="appCode" @on-change="onAppChange" style="width:227px" filterable transfer>
        <Option v-for="app in appList" :value="app.clientId" :key="app.clientId">{{ app.appName }}</Option>
      </Select>
    </div>
    <Transfer
      :data="allResources"
      :target-keys="AssignedResources"
      :list-style="listStyle"
      :titles="resourceList"
      :operations="operationsList"
      :render-format="render"
      filterable
      @on-change="handleChange"
    ></Transfer>
  </div>
</template>
<script>
import locales from "./locales.js";
import { queryResouceList } from "@/api/resourceApi.js";
import roleAPI from "@/api/roleApi.js";
import { searchAppListByTenantCode } from "@/api/applicationApi.js";
export default {
  name: "permissioneditforapprole",
  mixins: [locales],
  props: {
    roleId: {
      type: String,
      default() {
        return "";
      }
    },
    roleAppCode: {
      type: String,
      default() {
        return "";
      }
    },
    tenantCode: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      appList: [],
      appCode: this.roleAppCode,
      allResources: [],
      AssignedResources: [],
      listStyle: {
        width: "300px",
        height: "399px"
      },
      isChange: false,
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.close();
          }
        }
      ]
    };
  },
  computed: {
    resourceList() {
      return [this.$t("module.role.unResourceList"), this.$t("module.role.alResourceList")];
    },
    operationsList() {
      return [this.$t("common.delete"), this.$t("common.create")];
    }
  },
  created: function() {
    this.init();
    this.$emit("SetTitle", this.$t("module.role.permissionMaList"));
    this.$emit("SetPageWidth", 770);
    this.$emit("SetPageActions", this.actions);
  },
  methods: {
    render(item) {
      if (item.appEnabled == 0 || item.enabled == 0) {
        return "<span style='color:#bcbcbc'>" + item.label + "</span>";
      } else {
        return "<span>" + item.label + "</span>";
      }
    },
    init() {
      // 查询应用
      this.initApplication();
      // 角色有所属应用
      if (this.roleAppCode) {
        // 查询所有资源
        this.queryAllResource(this.roleAppCode);
        // 查询已分配的资源
        this.queryAssignedResource();
      }
    },
    initApplication() {
      // 查询应用
      searchAppListByTenantCode({
        pageNum: 1,
        pageSize: 200,
        condition: {
          tenantCode: this.tenantCode,
          enabled: 1
        }
      }).then(({ data: { records } }) => {
        this.appList = records;
      });
    },
    queryAllResource(appCode) {
      //查询参数
      let param = {
        condition: {
          applicationId: appCode,
          publicFlag: 1,
          enabled: 1 //0-有效，1-无效。这里只取有效资源
        },
        pageNum: 1,
        pageSize: 999
      };
      // $store.dispatch("QueryResouceList", param)
      queryResouceList(param).then(res => {
        res.records.forEach(resouce => {
          resouce.key = resouce.id;
          resouce.label = resouce.resourceName + "-" + resouce.resourceCode;
        });
        this.allResources = res.records.concat(this.allResources);
      });
    },
    queryAssignedResource() {
      roleAPI.queryAssignedApiResource(this.roleId, this.appCode).then(data => {
        // this.AssignedResources = data.map(resouce => resouce.resourceId);
        // 由于待分配数据只显示有效资源，所以当已分配数据的资源无效了，待分配里也不再返回。但组件逻辑会将已分配数据id作为key值，将待分配数据里将含有这些 key 值的数据筛选到右边，但由于待分配里不再返回无效数据，因此无法筛选到。
        // 所以将应用appEnabled无效或者资源enabled无效的数据追加到待分配数据里，以供已分配数据的key值索引
        this.AssignedResources = data.map(item => {
          if (item.appEnabled == 0 || item.enabled == 0) {
            this.allResources.push({
              key: item.resourceId,
              label: item.resourceName + "-" + item.resourceCode,
              appEnabled: item.appEnabled,
              enabled: item.enabled
            });
          }
          return item.resourceId;
        });
      });
    },
    handleChange(newTargetKeys) {
      this.isChange = true;
      this.AssignedResources = newTargetKeys;
    },
    save() {
      if (!this.appCode) {
        this.$message.error({
          content: this.$t("module.role.selectSourceApplication"),
          duration: 3
        });
        return;
      }
      // 角色没有所属应用
      // 保存角色所属应用
      roleAPI.saveRoleApp({
        id: this.roleId,
        appId: this.appCode
      });
      this.actions[0].loading = true;
      // 保存角色分配资源
      roleAPI
        .saveAssignedApiResource({
          appId: this.appCode,
          roleId: this.roleId,
          resourceId: this.AssignedResources
        })
        .then(data => {
          this.$message.success({
            content: this.$t("module.role.assignSucccess"),
            duration: 3
          });
          this.$emit("Close", true);
        })
        .catch(() => {
          this.actions[0].loading = false;
        });
    },
    close() {
      if (this.isChange) {
        new $confirm(this.$t("module.role.assignTip"), this).then(() => {
          this.$emit("Close");
        });
      } else {
        this.$emit("Close");
      }
    },
    onAppChange(value) {
      // 查询所有资源
      this.queryAllResource(value);
      // 清空未选资源
      this.allResources = [];
      // 清空已选资源
      this.AssignedResources = [];
      this.queryAssignedResource();
    }
  },
  watch: {},
  directives: {}
};
</script>
<style lang="less">
.SelectApp {
  margin-bottom: 5px;
  span {
    font-size: 14px;
  }
}
</style>
